class Rotate3 extends egret.DisplayObjectContainer {
    private balls: Array<Ball>
    private numBalls: number = 10
    private rotating: number = 0.001
    private touchX: number = 0
    private touchY: number = 0

    public constructor() {
        super()
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this)
    }

    private onAddToStage(event: egret.Event) {
        this.balls = new Array<Ball>()
        for (let i = 0; i < this.numBalls; ++i) {
            let ball = new Ball()
            ball.x = Math.random() * this.stage.stageWidth
            ball.y = Math.random() * this.stage.stageHeight
            this.balls.push(ball)
            this.addChild(ball)
        }
        this.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.trackTouch, this)
        this.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.trackTouch, this)
        this.stage.addEventListener(egret.TouchEvent.TOUCH_END, this.trackTouch, this)
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
    }

    private onEnterFrame(event: Event) {
        let angle: number = (this.touchX - this.stage.stageWidth / 2) * this.rotating
        let cos: number = Math.cos(angle)
        let sin: number = Math.sin(angle)

        for (let i = 0; i < this.numBalls; ++i) {
            let ball: Ball = this.balls[i]
            this.rotate(cos, sin, ball)
        }
    }

    private rotate(cos: number, sin: number, ball: Ball) {
        let x1: number = ball.x - this.stage.stageWidth / 2
        let y1: number = ball.y - this.stage.stageHeight / 2
        let x2: number = cos * x1 - sin * y1
        let y2: number = cos * y1 + sin * x1
        ball.x = this.stage.stageWidth / 2 + x2
        ball.y = this.stage.stageHeight / 2 + y2
    }

    private trackTouch(evt:egret.TouchEvent) {
        this.touchX = evt.stageX
        this.touchY = evt.stageY
    }
}